package com.pdool.game.util;

import com.google.protobuf.GeneratedMessageV3;
import com.pdool.game.logic.mgr.UserMgr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * session工具类
 */
@Slf4j
public class SessionUtil {

    public static void pushMsg(long roleId, int headId, GeneratedMessageV3 msg) {
        if (isRobot(roleId)) {
            return;
        }
        WebSocketSession webSocketSession = UserMgr.getInstance().getSessionMap().get(roleId);
        pushMsg(webSocketSession, headId, msg);
    }

    public static boolean isRobot(long roleId) {
        return roleId < 0;
    }

    public static void pushMsg(WebSocketSession webSocketSession, int headId, GeneratedMessageV3 msg) {
        try {
            if (webSocketSession != null && webSocketSession.isOpen()) {
                synchronized (webSocketSession) {
                    byte[] build = msg.toBuilder().build().toByteArray();
                    ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES + build.length);
                    buffer.putInt(headId);
                    buffer.put(build);
                    BinaryMessage binaryMessage = new BinaryMessage(buffer.array());
                    webSocketSession.sendMessage(binaryMessage);
                }
            }
        } catch (IOException e) {
            log.error("", e);
        }
    }

    /**
     * 关闭session
     *
     * @param session
     */
    public static void closeSession(WebSocketSession session) {
        try {
            if (session != null){
                session.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
